package com.haoshuang.zhouzhoubang.ui.page.shop.order.detail

import android.annotation.SuppressLint
import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import androidx.recyclerview.widget.LinearLayoutManager
import com.alipay.sdk.app.PayTask
import com.gyf.immersionbar.ktx.immersionBar
import com.haoshuang.zhouzhoubang.config.Config
import com.haoshuang.zhouzhoubang.databinding.ActivityShopOrderDetailBinding
import com.haoshuang.zhouzhoubang.model.bean.OrderBean8
import com.haoshuang.zhouzhoubang.ui.dialog.PayDialog
import com.haoshuang.zhouzhoubang.ui.page.shop.order.child.ShopOrderListAdapter2
import com.haoshuang.zhouzhoubang.utils.Event
import com.haoshuang.zhouzhoubang.utils.PayResult
import com.haoshuang.zhouzhoubang.utils.PaymentUtil
import com.haoshuang.zhouzhoubang.utils.PreferenceUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.visible
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 订单详情
 */
class ShopOrderDetailActivity :
    BaseActivity<ShopOrderDetailViewModel, ActivityShopOrderDetailBinding>() {

    override fun initView(savedInstanceState: Bundle?) {
        binding.appBar.leftImageView().click { finish() }
        binding.appBar.title = "待收货"
        immersionBar {
            statusBarDarkFont(true) //状态栏字体 true为深色 false为亮色
            transparentStatusBar()
            titleBarMarginTop(binding.appBar)
        }
    }

    var ids = 0
    var status4 = 0
    var list = arrayListOf<OrderBean8.CartInfo>()
    lateinit var adapter: ShopOrderListAdapter2
    override fun initData() {
        EventBus.getDefault().register(this)
        ids = intent.getIntExtra("ids", 0)
        vm.getData("id" to ids)
        binding.apply {
            llDh.clickWithTrigger {

                var myClipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                myClipboard.setPrimaryClip(
                    ClipData.newPlainText(
                        "content",
                        expressId.text.toString()
                    )
                )
                toast("复制成功")
            }
            adapter = ShopOrderListAdapter2(list)
            rvList.layoutManager = LinearLayoutManager(this@ShopOrderDetailActivity)
            rvList.adapter = adapter
            tvRightButton.clickWithTrigger {
                if (status4 == 0) {
                    Pay(ids)
                } else {
                    vm.getData3("id" to ids)
                }
            }
            tvLeftButton.clickWithTrigger {
                vm.getData2("id" to ids)
            }
        }
    }

    private val SDK_PAY_FLAG = 1

    @SuppressLint("HandlerLeak")
    var mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult = PayResult(msg.obj as Map<String?, String?>)

                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo = payResult.result // 同步返回需要验证的信息
                    val resultStatus = payResult.resultStatus
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        toast("支付成功")
                        // startPage<SuccessActivity>()
                        vm.getData("id" to ids)

                    } else {
                        toast("支付失败")

                    }
                }

                else -> {}
            }
        }
    }

    fun payAlipay(mContext: Context?, orderNo: String) {
        val payRunnable = Runnable {
            val alipay = PayTask(mContext as Activity?)
            val result = alipay.payV2(orderNo, true)
            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }
        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }

    //订阅方法，当接收到事件的时候，会调用该方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageEvent: Event) {

        if (messageEvent.code == 8005) {
            toast("支付成功")

            finish()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    fun Pay(id: Int) {
        XPopup.Builder(this@ShopOrderDetailActivity)
            .dismissOnTouchOutside(false)
            .asCustom(PayDialog(this@ShopOrderDetailActivity) {
                if (it == 1) {
                    vm.getData41(
                        "id" to id, "payType" to it
                    )
                } else {
                    vm.getData4(
                        "id" to id, "payType" to it
                    )
                }

                /*   vm.getData4(
                       "id" to id
                   )*/
            })
            .show()
    }

    override fun startObserve() {
        vm.getData41.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code != "402") {
                    toast(msg)
                }
            }
            onSuccess {
                dismissLoading()
                var api =
                    WXAPIFactory.createWXAPI(this@ShopOrderDetailActivity, Config.WX_ID, false)
                PreferenceUtils.putString("Wxpay", "3")
                PaymentUtil.payWxPayment(api, it)
            }
        }
        vm.getData4.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code != "402") {
                    toast(msg)
                }
            }
            onSuccess {
                dismissLoading()
                payAlipay(this@ShopOrderDetailActivity, it?.body!!)
            }
        }
        vm.getData2.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code != "402") {
                    toast(msg)
                }
            }
            onSuccess {
                dismissLoading()
                vm.getData("id" to ids)
            }
        }
        vm.getData3.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code != "402") {
                    toast(msg)
                }
            }
            onSuccess {
                dismissLoading()
                vm.getData("id" to ids)
            }
        }
        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code != "402") {
                    toast(msg)
                }
            }
            onSuccess {
                dismissLoading()
                if (it != null) {
                    list.clear()
                    list.addAll(it.cartInfo)
                    adapter.notifyDataSetChanged()
                    binding.apply {
                        if (it.status == 2 || it.status == 3) {
                            tvFf.visible()
                            llDh.visible()
                            llMc.visible()
                        } else {
                            tvFf.gone()
                            llDh.gone()
                            llMc.gone()
                        }
                        status4 = it.status
                        when (it.status) {
                            0 -> {
                                appBar.title = "待付款"
                                tvLeftButton.visible()
                                tvRightButton.visible()
                                tvRightButton.text = "立即支付"
                                clBottomBarOne.visible()
                            }

                            1 -> {
                                appBar.title = "待发货"
                                tvLeftButton.gone()
                                tvRightButton.gone()
                                tvRightButton.text = "立即支付"
                                clBottomBarOne.gone()
                            }

                            2 -> {
                                appBar.title = "待收货"
                                tvLeftButton.gone()
                                tvRightButton.visible()
                                tvRightButton.text = "确认收货"
                                clBottomBarOne.visible()
                            }

                            3 -> {
                                appBar.title = "已完成"
                                tvLeftButton.gone()
                                tvRightButton.gone()
                                clBottomBarOne.gone()
                            }

                            4 -> {
                                appBar.title = "已取消"
                                tvLeftButton.gone()
                                tvRightButton.gone()
                                clBottomBarOne.gone()
                            }

                            else -> {
                                appBar.title = "已完成"
                                tvLeftButton.gone()
                                tvRightButton.gone()
                                clBottomBarOne.gone()
                            }
                        }
                        tvRemark.text = it.remark
                        expressId.text = it.express_id
                        addTime.text = it.add_time
                        expressName.text = it.express_name
                        orderId.text = it.order_id
                        payPostage.text = "¥" + it.pay_postage
                        payPrice.text = "¥" + it.pay_price
                        if (it.delivery_method == 2){
                            tvAdr.text = it.pickup_address
                            tvName.text = "自提点"
                            llPostage.gone()
                        }else {
                            tvAdr.text = it.user_address
                            tvName.text = "${it.real_name}     ${it.user_phone}"
                            llPostage.visible()
                        }
                    }

                }
            }
        }
    }

}